<template>
  <el-dialog :model-value="show" title="分配角色">
    <el-select v-model="hasRoles" multiple>
      <el-option
        :value="item.id"
        v-for="item in allRole"
        :key="item.id"
        :label="item.name"
      />
    </el-select>
    <template #footer>
      <el-button>取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getUserRoleApi, getAllRoleListApi, allocRoleForAdminApi } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, watch } from "vue";

const props = defineProps({
  show: {
    type: Boolean,
  },
  id: {
    type: Number,
    default: 0,
  },
});

const allRole = ref<Role[]>([]);
getAllRoleListApi().then((res) => {
  if (res.code === 200) {
    allRole.value = res.data;
  }
});

const hasRoles = ref<number[]>([]);

watch(
  () => props.id,
  () => {
    if (props.id !== 0) {
      getUserRoleApi(props.id).then((res) => {
        if (res.code === 200) {
          // 获取到了用户已经有的角色
          // 渲染到 el-select 里面
          hasRoles.value = res.data.map((item) => item.id);
        }
      });
    }
  }
);

const submit = () => {
  ElMessageBox.confirm("确定要分配角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    allocRoleForAdminApi({
      adminId: props.id,
      roleIds: hasRoles.value,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success("分配成功");
        // 关闭弹出框
      }
    });
  });
};
</script>
<style lang="less" scoped></style>
